<template>
<div>
  <home-header></home-header>
  <home-swiper :list="swiperList"></home-swiper>
  <home-icons :list="iconList"></home-icons>
  <home-recommand :list="recommendList"></home-recommand>
  <home-weekend :list="weekendList"></home-weekend>
</div>
</template>

<script>
import HomeHeader from "./components/Header";
import HomeSwiper from "./components/Swiper";
import HomeIcons from "./components/Icons";
import HomeRecommand from "./components/Recommand";
import HomeWeekend from "./components/Weekend";
import axios from "axios";
import { mapState } from "vuex";
export default {
  name: "Home",
  data() {
    return {
      iconList: [],
      recommendList: [],
      swiperList: [],
      weekendList: [],
      // 存储上一个城市
      lastCity: ''
    };
  },
  computed: {
    // 展开运算符, 将store.state.city 映射到 this.city 上
    ...mapState(['city'])
  },
  methods: {
    getHomeInfo() {
      axios.get("/api/index.json?city=" + this.city).then(res => {
        const data = res.data.data;
        this.iconList = data.iconList;
        this.recommendList = data.recommendList;
        this.swiperList = data.swiperList;
        this.weekendList = data.weekendList;
      });
    }
  },
  mounted() {
    // 组件挂载后, 将lastCity赋值为当前的城市
    this.lastCity = this.city
    this.getHomeInfo()
  },
  activated(){
    // 如果上一次选择的城市和当前城市不一样的时候, 再次发ajax请求获取数据
    if(this.lastCity !== this.city){
      // 城市不一样的时候, 将当前城市赋值给lastCity
      this.lastCity = this.city
      // 发送ajax请求
      this.getHomeInfo()
    }
  },
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommand,
    HomeWeekend
  }
};
</script>

<style scoped>
</style> 